package service

import (
	"bufio"
	"log"
	"os"
	"path/filepath"
)

type FileSvr struct {
}

func NewFileSvr() *FileSvr {
	return &FileSvr{}
}

func (s *FileSvr) CreateFile(fileName string) (f *os.File, err error) {
	// 获取文件的目录路径
	dir := filepath.Dir(fileName)

	// 创建目录（包括所有中间目录）
	if err := os.MkdirAll(dir, 0755); err != nil {
		log.Fatalf("MkdirAll failed err=%s\n", err)
	}

	f, err = os.Create(fileName)
	if err != nil {
		log.Fatalf("create file failed err=%s\n", err)
	}
	log.Printf("create file succeed!")
	return f, err
}

func (s *FileSvr) WriteFile(filename string, byte []byte) error {
	file, err := os.OpenFile(filename, os.O_WRONLY, 0666)
	if err != nil {
		return err
	}

	// 为这个文件创建buffered writer
	bufferedWriter := bufio.NewWriter(file)

	// 写字符串到buffer
	contantStr := string(byte)
	bytesWritten, err := bufferedWriter.WriteString(
		contantStr,
	)
	if err != nil {
		return err
	}
	log.Printf("Bytes written: %d\n", bytesWritten)

	// 写内存buffer到硬盘
	err = bufferedWriter.Flush()
	if err != nil {
		return err
	}

	file.Close()
	return nil
}
